package com.example.enjoyfood

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class RegisterActivity : AppCompatActivity() {

    private lateinit var emailEditText: EditText
    private lateinit var passwordEditText: EditText
    private lateinit var registerButton: Button
    private lateinit var backToLoginButton: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_register)

        // 调试信息
        Log.d("RegisterActivity", "Layout loaded: activity_register.xml")

        emailEditText = findViewById(R.id.email_edit_text)
        passwordEditText = findViewById(R.id.password_edit_text)
        registerButton = findViewById(R.id.register_button)
        backToLoginButton = findViewById(R.id.back_to_login_button)

        registerButton.setOnClickListener {
            register()
        }
        backToLoginButton.setOnClickListener {
            backToLogin()
        }
    }

    private fun register() {
        val email = emailEditText.text.toString().trim()
        val password = passwordEditText.text.toString().trim()

        if (email.isNotEmpty() && password.isNotEmpty()) {
            // 假设注册成功
            saveUserCredentials(email, password)
            Toast.makeText(this, "注册成功！", Toast.LENGTH_SHORT).show()
            // 返回登录界面
            backToLogin()
        } else {
            Toast.makeText(this, "请填写所有字段", Toast.LENGTH_SHORT).show()
        }
    }

    private fun saveUserCredentials(email: String, password: String) {
        val sharedPreferences = getSharedPreferences("user_profile", MODE_PRIVATE)
        val editor = sharedPreferences.edit()
        editor.putString("nickname", email)
        editor.putString("password", password)
        editor.apply()
        // 调试信息
        Toast.makeText(this, "保存的用户信息: $email, $password", Toast.LENGTH_SHORT).show()
    }

    private fun backToLogin() {
        val intent = Intent(this, LoginActivity::class.java)
        startActivity(intent)
        finish() // 可选：结束注册活动
    }
}